package top.haijunit.sample.navi.utils;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.io.file.FileNameUtil;
import cn.hutool.core.util.StrUtil;
import lombok.experimental.UtilityClass;

import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * @author zhanghaijun
 * @date 2024/7/5 18:05
 * @description [一句话描述该类的功能]
 */
@UtilityClass
public class PathUtil {

    public static String getName(String filePath) {
        return FileNameUtil.getName(PathUtil.join(filePath));
    }

    public static String getParent(String filePath) {
        List<String> list = StrUtil.splitTrim(PathUtil.join(filePath), "/");
        if (list.isEmpty()) {
            return null;
        }
        if (list.size() == 1) {
            return "/";
        }
        return String.join("/", CollUtil.sub(list, 0, list.size() - 1));
    }

    /**
     * 3,2,directory,a -> 3/2/directory/a
     * 3,2,directory,/ -> 3/2/directory
     * /,a -> /a
     * a,/ -> a
     *
     * @param paths 路径
     * @return 处理完毕的路径
     */
    public static String join(Object... paths) {
        if (paths == null || paths.length == 0) {
            return "";
        }
        String path = Stream.of(paths).map(String::valueOf).filter(StrUtil::isNotBlank).collect(Collectors.joining("/"));
        if (StrUtil.isBlank(path)) {
            return "";
        }
        return path.replaceAll("/+", "/").replaceAll("/$", "");
    }

}
